<template>
  <div v-for="blog in blogs" :key="blog.id" class="card">
    <div class="blog-info">
      <div class="blog-info-title" @click="handleclickRead(blog.id)">
        {{ blog.title }}
      </div>
      <div class="blog-info-sub">
        <div>发表于 {{ formatDate(blog.updateTime) }}</div>
        <div mx-3>|</div>
        <div class="blog-info-category" @click="handleclickCategory(blog.categoryId)">
          {{ blog.categoryName }}
        </div>
      </div>
      <div class="blog-info-description">{{ blog.description }}</div>
    </div>
    <div class="blog-picture">
      <img id="bg" :src="bg.url" />
    </div>
  </div>
  <div class="pagination">
    <n-pagination
      v-if="showPage"
      v-model:page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :item-count="pagination.itemCount"
      :page-sizes="pagination.pageSizes"
      :show-size-picker="pagination.showSizePicker"
      @update:page-size="onPageSizeChange"
      @update:page="onPageChange"
    />
  </div>
</template>

<script setup>
import { getBlogs } from '@/api/blog.js'
import { formatDate, scrollTop, scrollHomePage } from '@/utils/'
import { getTagDict, getCategoryDict } from '@/api/dict.js'
import { useCategoryStore, useTagStore } from '@/store'
import { getBackgroyndImage } from '/settings/background.js'

onMounted(() => {
  handleSearch()
  getDict()
})

// onActivated(() => {
//   console.log('onActivated')
//   handleSearch()
//   getDict()
// })

const bg = computed(() => {
  return getBackgroyndImage('home')
})

const props = defineProps({
  remote: {
    type: Boolean,
    default: true,
  },
  isPagination: {
    type: Boolean,
    default: true,
  },
  searchType: {
    type: String,
    default: '',
  },
  searchValue: {
    type: String,
    default: '',
  },
})

const pagination = reactive({
  page: 1,
  pageSize: 5,
  prefix({ itemCount }) {
    return `共 ${itemCount} 项`
  },
  pageSizes: [5, 10, 20],
  showSizePicker: true,
})

const blogs = ref({})
const router = useRouter()
const loading = ref(false)
const categoryDict = useCategoryStore()
const tagDict = useTagStore()
const showPage = ref(true)

async function handleQuery() {
  try {
    loading.value = true
    let paginationParams = {}
    let extraParams = {}
    // 如果非分页模式或者使用前端分页,则无需传分页参数
    if (props.isPagination && props.remote) {
      paginationParams = { pageNo: pagination.page, pageSize: pagination.pageSize }
    }
    if (props.searchType && props.searchValue) {
      extraParams = { type: props.searchType, value: props.searchValue }
    }
    const { data } = await getBlogs({ ...extraParams, ...paginationParams })
    blogs.value = data?.pageData || data
    pagination.itemCount = data.total ?? data.length
    if (pagination.itemCount <= 0) {
      showPage.value = false
    } else {
      showPage.value = true
    }
  } catch (error) {
    console.log('error')
    blogs.value = []
    pagination.itemCount = 0
  } finally {
    loading.value = false
  }
}

function getImageUrl(url) {
  return new URL(url, import.meta.url).href
}

function onPageChange(currentPage) {
  pagination.page = currentPage
  scrollHomePage()
  if (props.remote) {
    handleQuery()
  }
}

function onPageSizeChange(pageSize) {
  pagination.pageSize = pageSize
  scrollHomePage()
  if (props.remote) {
    handleQuery()
  }
}

function handleSearch() {
  pagination.page = 1
  handleQuery()
}

function handleclickRead(blogId) {
  router.push(`/blog/${blogId}`)
}

function handleclickCategory(categoryId) {
  router.push(`/category/${categoryId}`)
}

function getDict() {
  getTagDict().then((res) => {
    tagDict.setTag(res.data)
  })
  getCategoryDict().then((res) => {
    categoryDict.setCategory(res.data)
  })
}

defineExpose({
  pagination,
  handleQuery,
})
</script>

<style scoped>
.card {
  display: flex;
  height: 240px;
  padding: 0;
  cursor: pointer;
  overflow: hidden;
}

.card .blog-info {
  display: inline-block;
  width: 55%;
  text-align: left;
  padding: 0 40px;
  margin: auto;
  line-height: 30px;
}
.card .blog-info-title {
  font-size: 30px;
  /* font-weight: bold; */
}

.card .blog-info-title:hover {
  font-size: 25px;
  font-weight: bold;
  color: #278dfb;
}

.card .blog-info-sub {
  margin-top: 5px;
  display: flex;
  font-size: 12px;
}

.card .blog-info-sub .blog-info-category:hover {
  cursor: pointer;
  text-decoration: underline;
}

.card .blog-info-description {
  font-size: 15px;
}

.card .blog-picture {
  width: 45%;
  border-radius: 0% 2% 2% 0%;
  overflow: hidden;
}
.card .blog-picture img {
  width: 100%;
  height: 100%;
  transition: all 0.6s;
  object-fit: cover;
  object-position: center;
}

.card:hover #bg {
  transform: scale(1.2);
}

.pagination {
  padding: 0 10px;
  display: flex;
  justify-content: flex-end;
}
</style>
